<?php


class Api_lottery_mdl extends CI_Model
{
	
	
	const TBL_LOTTERY = 'cj_lottery';
	
	
	public function __construct()
	{
		parent::__construct();
	}
	
	public function outputdata($data)
	{
		$rewardid = intval($data['DRAWNO']);
		
		$lotteryn = array();
		$lotteryn = $this->db->select('lottery.*,reward.enabled,reward.id')
							->from(self::TBL_LOTTERY.' as lottery')
							->join('cj_reward as reward','lottery.rewardid = reward.id')
							->where('rewardid',$rewardid)
							//->get(self::TBL_LOTTERY)->result_array();
							->get()
							->result_array();

		if(!empty($lotteryn)){
			foreach($lotteryn as $v){

				if(!empty($v['uid']))
				{
					$haved[] =$v['rnum'];
				}
			}
					
		}	
		
		header('Content-Type:text/html; charset=utf-8', false);
		
		$outputdata['TAG'] = $data['TAG'];
		$outputdata['DRAWNO'] = $data['DRAWNO'];
		$outputdata['USERID'] = $data['USERID'];
		$outputdata['EMAIL'] = $data['EMAIL'];
		$outputdata['TOKEN'] = $data['TOKEN'];
		$outputdata['DRAWSTATUS'] = empty($lotteryn[0]['enabled']) ? 2 : $lotteryn[0]['enabled'];
		$outputdata['PURCHASED']= empty($haved) ? '' : implode(',', $haved);
		$outputdata['REWARDED'] = $this->get_user_join_reward($data['USERID'],$data['DRAWNO']);
	
		echo json_encode($outputdata);
	}
	
	/**
	 * 取得用户参加过未结束的活动，以及获奖情况
	 */
	
	private function get_user_join_reward($uid,$rewardid)
	{
		$lotteryn = $this->db->select('lottery.*,product.productname,product.ptype,product.id,users.txusername,users.uid,reward.enabled')
						->from(self::TBL_LOTTERY.' as lottery')
						->join('cj_reward as reward','lottery.rewardid = reward.id')
						->join('cj_products as product','product.id = lottery.productid','left')
						->join('cj_users as users','users.uid = lottery.uid')
						->where('reward.id',$rewardid)
						->where('lottery.uid',$uid)
						->get()
						->result_array();
		$tmp = array();		
		if(!empty($lotteryn))
		{
			foreach($lotteryn as $v)
			{
				$n['NUM'] = (int)$v['rnum'];
				$n['PRODUCTID'] = (int)$v['productid'];
				$n['PRODUCTNAME'] = $v['productname'];
				$n['TYPE'] = (int)$v['ptype'];
				$tmp[$v['rewardid']][] = $n;
			}
		}
		//print_r($tmp);
		return $tmp;
	}
}